<?php

namespace App\Http\Admin\Logics;

use App\Models\Models\System\SystemAccount;
use App\Models\Models\System\SystemAccountAuth;
use App\Models\Models\System\SystemMenu;
use Exception as GlobalException;
use think\Exception;

class MenuLogic
{
	public static function getListWithCount($where=[], $field='*', $page=1, $count=10, $order='') {
		return SystemMenu::getListWithCountCommon($where, $field, $page, $count, $order);
	}

	public static function getAll($where=[]) {
		return SystemMenu::getAllCommon($where, '*', SystemMenu::ORDER_DEFAULT);
	}

    public static function getTree($accountId) {
        // 查询当前用户的菜单ID
        $auth = SystemAccountAuth::getOneByAccount($accountId);
        $menuIdChecked = $auth->getMenuId();

        $where = [
            'status' => SystemMenu::STATUS_SHOW,
        ];
        $data = SystemMenu::getAllCommon($where, '*', ['pid', 'asc']);

        $treeList = [];
        foreach($data as $v) {
            /* @var SystemMenu $v */

            $id = $v->getId();
            $pid = $v->getPid();

            $info = [
                'id'    => $id,
                'title' => $v->getTitle(),
                'spread'=> true,
                'children'  => [],
            ];
            if(in_array($id, $menuIdChecked)) {
                $info['checked'] = true;
            }

            if($pid == 0) {
                $info['checked'] = false;
                $treeList[$id] = $info;
                continue;
            }

            if(array_key_exists($pid, $treeList)) {
                $treeList[$pid]['children'][] = $info;
                continue;
            }
            throw new GlobalException($v->getTitle() . ' 菜单树形结构有问题,联系技术');
        }

        return $treeList;
    }

	public static function getAllStatus($accountId) {
        if($accountId == SystemAccount::USER_SUPER) {
            // 超级管理员直接返回全部菜单
            return SystemMenu::getAllStatus();
        }
        // 获取权限菜单
        $menuIds = SystemAccountAuth::getMenuIdByAccountId($accountId);

        // where in
		return SystemMenu::getAllStatus($menuIds);
	}

	public static function del($id) {
		return SystemMenu::delByPkCommon($id);
	}

	public static function update($data) {
		return SystemMenu::updateCommon($data);
	}

	public static function add($data) {
		return SystemMenu::addCommon($data);
	}

	public static function getInfo($id) {
		return SystemMenu::getLineByPkCommon($id);
	}

	public static function status($id, $status) {
		return SystemMenu::status($id, $status);
	}
}